#include "srfacegate.h"
#include <QDebug>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QRegExpValidator>
#include <QJsonObject>
#include <QPainter>
#include <QColor>
#include <QKeyEvent>


#include "qrcodegenerate.h"

#include "global.h"
#include "commonhelper.h"
#include "oeprompt.h"
#include "res.h"

SRFacegate::SRFacegate(QWidget *parent)
    : QDialog(parent)
{
    /////////////// 基础参数初始化 ///////////////

    setFixedSize(750,400);
    setWindowFlags(/*Qt::Tool|*/Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);



    /////////////// 其他初始化 ///////////////
    // 控件初始化
    labBackground_ = new QLabel(this);
    editLicence_ = new QLineEdit(this);
    editLicence_->setFocus(); // 默认选中
    btnClose_ = new QPushButton(QString("×"),this);
    btnGotQrCode_ = new QPushButton(QString("确认激活"),this);
    labQrCode_ = new QrcodeGenerate(this);
//    labQrCode_ = new QLabel(this);
    labBackground_->show();
    // 资源初始化


    /////////////// 信号链接 ///////////////
    connect(btnClose_,SIGNAL(clicked()),
            this,SLOT(reject()));
    connect(btnGotQrCode_,SIGNAL(clicked()),
            this,SLOT(onGotClick()));
    connect(editLicence_,SIGNAL(textChanged(QString)),
            this,SLOT(onLicenceEditChange(QString)));


    /////////////// 布局 ///////////////
    btnClose_->setFixedSize(50,30);
    editLicence_->setFixedSize(487,33);


    // 二维码布局
    labQrCode_->setGeometry(285,35,180,180);



    // 确认按钮布局
    btnGotQrCode_->setFixedSize(100,30);
    btnGotQrCode_->move(width() / 2 - btnGotQrCode_->width() / 3 - 15,
                        height() - btnGotQrCode_->height() - 30);
    // 授权码输入框布局
    editLicence_->setFont(QFont("微软雅黑",16));
    editLicence_->setPlaceholderText(tr("请输入序列号"));
    editLicence_->setStyleSheet("font-size:24px;");
    QRegExp regQuote("[0-9a-zA-Z]{1,100}");
    QRegExpValidator* quoteValidator = new QRegExpValidator(regQuote, this);
    editLicence_->setValidator(quoteValidator);
//    editLicence_->hide();
    editLicence_->move(130,255);
    // 关闭按钮
    btnClose_->move(width() - btnClose_->width() - 10, 10);


    labBackground_->setGeometry(0,0,width(),height());



    /////////////// 渲染 ///////////////
    // 二维码
    labQrCode_->setStyleSheet("background-color:white;");
    // 去除editline的外边框
    editLicence_->setStyleSheet("border:none;");

    QPixmap pixmap;
    pixmap.loadFromData(qt_res_bg_data, sizeof(qt_res_bg_data));
    labBackground_->setPixmap(pixmap);

    btnGotQrCode_->setStyleSheet("\
                                 QPushButton {\
                                   border-style:none;\
                                   border-left: 1px solid rgb(255, 255, 255);\
                                   border-top: 1px solid rgb(255, 255, 255);\
                                   border-bottom: 2px solid rgb(136, 163, 205);\
                                   border-right: 2px solid rgb(136, 163, 205);\
                                   color:rgb(255, 255, 255);\
                                   padding:3px;\
                                   border-radius: 2px;\
                                 }\
                                 QPushButton::pressed {\
                                   border-style:none;   \
                                   border-top: 2px solid rgb(136, 163, 205);\
                                   border-left: 2px solid rgb(136, 163, 205);\
                                   border-bottom: 1px solid rgb(255, 255, 255);\
                                   border-right: 1px solid rgb(255, 255, 255);\
                                   color:rgb(222, 222, 222);\
                                   padding:3px;\
                                   border-radius: 2px;\
                                 }");


    btnClose_->setStyleSheet("\
                             QPushButton {\
                               border-style:none;\
                               color:rgb(255, 255, 255);\
                               padding:3px;\
                               border-radius: 2px;\
                             }\
                              QPushButton::hover {\
                                border-style:none;\
                                 background-color: rgb(251, 97, 85);\
                                color:rgb(255, 255, 255);\
                                padding:3px;\
                                border-radius: 2px;\
                              }\
                              QPushButton::pressed {\
                                border-style:none;   \
                                background-color: rgb(204, 52, 40);\
                                color:rgb(255, 255, 255);\
                                padding:3px;\
                                border-radius: 1px;\
                              }");


}

SRFacegate::~SRFacegate()
{
}
void SRFacegate::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
        onGotClick();
        event->accept();
    }
    else if (event->key() == Qt::Key_Escape) {
        if (editLicence_->text().isEmpty())
            reject();
        else
            editLicence_->clear();

        event->accept();
    }
}

void SRFacegate::resizeEvent(QResizeEvent *)
{
    labBackground_->setGeometry(0,0,width(),height());
}

void SRFacegate::onGotClick()
{
    // 基础格式验证
    serialCode_ = editLicence_->text();
    if (serialCode_.isEmpty()) {
        OEPrompt* prompt = new OEPrompt(this, QString("授权码不能为空"));
        prompt->build();
        return;
    }
    QString serial_pattern("^\\w{4}-\\w{4}-\\w{4}-\\w{4}$");
    QRegExp rexp(serial_pattern);
    if (!rexp.exactMatch(serialCode_)) {
        OEPrompt* prompt = new OEPrompt(this, QString("请填写正确信息"));
        prompt->build();

        return;
    }

    serialCode_.replace("-","");

//    // 请求服务器网络验证
//    QJsonObject json_model = httpCheckSerial(serialCode_);

//    if (!json_model.contains("placeName")) {
//        OEPrompt* prompt = new OEPrompt(this,
//                                        QString("验证失败, 请确认序列号有效"),
//                                        300);
//        prompt->build();
//        return;
//    }

    // 本地验证
    if (!labQrCode_->serialCompare(serialCode_)) {
        OEPrompt* prompt = new OEPrompt(this,
                                        QString("验证失败, 请确认序列号有效"),
                                        300);
        prompt->build();
        return;
    }


    accept();
}




void SRFacegate::onLicenceEditChange(QString _info) {
    _info.replace("-", "");
    _info = _info.toUpper();
    int length = _info.size();
    int step = 5;

    for (int i=0; i<3; i++) {
        if (_info.size() >= step && _info.mid(step-1,1) != "-") {
            _info = _info.mid(0,step-1) + "-"
                    + _info.mid(step-1,length - step + 1);
            length++;
        }
        step += 5;
    }
    if (length > 19) {
        _info = _info.mid(0, 19);
    }
    editLicence_->setText(_info);
}


extern "C" __declspec(dllexport) int showRegister(QString stFile, QString msc, QString& serialCode) {
    settingFile = stFile;
    machineCode = msc;

    SRFacegate *registerDlg = new SRFacegate();
    int iRet = registerDlg->exec();
    if (QDialog::Accepted == iRet) {
        serialCode = registerDlg->getSerialCode();
    }

    delete registerDlg;

    return iRet;
}
